<?php

class LanguageService extends FServiceBase
{
    /**
     * Get a Language model given its ID
     *
     * @param int id Language ID
     * @return FServiceModel
     */
    public function get($params)
    {
        $model = Language::model()->findByPk($this->getParam($params, 'id', 0));
        if (!$model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Language', 'Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }

    /**
     * Add workflow after adding new support languages.
     *
     * @param mixed $params
     */
    public function addWorkflow($params)
    {
        $model = $this->getParam($params, 'model', null);
        $command = Yii::app()->db;
        if (!is_object($model))
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Language', 'Invalid model params.'));
        //Get the site default's' urls
        $site = Site::model()->findByPk($model->site_id);
        $siteDefaultUrls = SiteUrl::model()->findAllByAttributes(array('site_id' => $model->site_id, 'status' => true));
        $count = 0;
        if (count($siteDefaultUrls)) {
            foreach ($siteDefaultUrls as $siteUrl) {

                $liveUrl = $siteUrl->url . '/' . str_replace('_', '/', $model->locale_id);
                //Check exist domain, go here.
                $liveWf = array(
                    'name' => $model->locale_id . '_live',
                    'url' => $liveUrl,
                    'locale_id' => $model->locale_id,
                    'type' => Workflow::TYPE_FINAL,
                    'site_id' => $model->site_id,
                );
                if (!$this->isExistWorkflow($site->table_prefix . 'workflow', $liveUrl))
                    $count += $this->saveWorkflow($site->table_prefix . 'workflow', $liveWf);
            }
        }
        //Also add a dev workflow
        $result = $command->createCommand()->select('url')
            ->from($site->table_prefix . 'workflow')
            ->where('name=:name AND site_id=:siteId', array(
            ':name' => 'dev',
            ':siteId' => $model->site_id,
        ))->queryRow();
        if (count($result)) //If exist a default dev domain , get it.
            $domain = $result['url'];
        else //Get current dev domain
            $domain = parse_url(yii::app()->request->getHostInfo(), PHP_URL_HOST);
        //Check duplicate here.
        $devUrl = $domain . '/' . str_replace('_', '/', $model->locale_id);
        $devWf = array(
            'name' => $model->locale_id . '_dev',
            'url' => $devUrl,
            'locale_id' => $model->locale_id,
            'type' => Workflow::TYPE_INITITAL,
            'site_id' => $model->site_id,
        );
        if (!$this->isExistWorkflow($site->table_prefix . 'workflow', $devUrl))
            $count += $this->saveWorkflow($site->table_prefix . 'workflow', $devWf);
        return $this->result->processed('count', $count);
    }

    public function save($params)
    {
        /**
         * @var CModel
         */
        $model = $this->getModel($params['Language'], 'Language');
        $this->result->processed('model', $model);

        if (!$model->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Language', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly', 0) == TRUE)
            return $this->result;
        elseif (!$model->save())
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('Admin.Language', 'Error while saving submitted data into database.'));

        return $this->result;
    }


    public function delete($params)
    {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Language', 'Invalid ID.'));
        }

        if (!is_array($ids)) $ids = array($ids);
        foreach ($ids as $id) {
            $model = Language::model()->findByPk($id);
            /**
             * TODO: Check related data if this Language is deletable
             * This can be done in onBeforeDelete or here or in extensions
             *
            if (Related::model()->count("LanguageId = {$id}") > 0)
            $this->result->fail(ERROR_VIOLATING_BUSINESS_RULES, Yii::t('Admin.Language',"Cannot delete Language ID={$id} as it has related class data."));
            else
             */
            try {
                $model->delete();
            } catch (CDbException $ex) {
                $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
            }
        }
        return $this->result;
    }

    public function changeStatus($params)
    {
        $ids = $this->getParam($params, 'ids', array());
        $value = $this->getParam($params, 'value', false);
        $value = $value == 'Y'
            ? true : false;
        if (count($ids) <= 0)
            return $this->result;

        $criteria = new CDbCriteria();
        $criteria->addInCondition('id', $ids);
        Language::model()->updateAll(array('status' => $value), $criteria);

        return $this->result;
    }

    /**
     * @param $tableName
     * @param $data
     * @return int
     */
    protected function saveWorkflow($tableName, $data)
    {
        $command = Yii::app()->db;
        return $command->createCommand()->insert($tableName, $data);
    }

    protected function isExistWorkflow($tableName, $url)
    {
        $command = Yii::app()->db;
        $result = $command->createCommand()->select('url')
            ->from($tableName)
            ->where('url=:url', array(':url' => $url))
            ->queryRow();
        if ($result === false)
            return false;
        else return true;
    }
}